package com.zsl.swing.redis.desktop.window.dialog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zsl.swing.redis.desktop.common.IconPaths;
import com.zsl.swing.redis.desktop.model.KeyEntity;
import com.zsl.swing.redis.desktop.model.NodeEntity;
import com.zsl.swing.redis.desktop.type.BtnOptEnum;
import com.zsl.swing.redis.desktop.type.DbOptEnum;
import com.zsl.swing.redis.desktop.type.RedisTypeEnum;
import com.zsl.swing.redis.desktop.utils.*;
import com.zsl.swing.redis.desktop.window.ZslRedisDesktopMainWindow;
import com.zsl.swing.redis.desktop.window.builder.ConfirmCancelBtnPanelBuilder;
import com.zsl.swing.redis.desktop.window.panel.ZslKeyValuePanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

public class ZslKeyChangeDialog extends JDialog {

    private static final Image CREATE_IMAGE = IconUtils.getScaleImage(IconPaths.DETAIL_ICON, 30, 30);

    private final NodeEntity dbEntity;

    private final DbOptEnum optEnum;

    private final KeyEntity keyEntity;

    private ZslKeyValuePanel zslKeyValuePanel;

    private static final int WIDTH = 1000;

    private static final int HEIGHT = 800;

    public ZslKeyChangeDialog(DbOptEnum optEnum, NodeEntity dbEntity, KeyEntity keyEntity){
        super(ZslRedisDesktopMainWindow.getMainWindow());

        this.optEnum = optEnum;
        this.dbEntity = dbEntity;
        this.keyEntity = keyEntity;

        this.initPanel();

    }

    private void initPanel() {
        this.setIconImage(CREATE_IMAGE);
        this.setTitle(optEnum.getText());
        this.setSize(new Dimension(WIDTH, HEIGHT));

        int x = CommonUtils.maxWidth()/2 - WIDTH/2;
        int y = CommonUtils.maxHeight()/2 - HEIGHT/2;
        this.setLocation(x, y);

        if(optEnum == DbOptEnum.ADD){
            this.zslKeyValuePanel = new ZslKeyValuePanel(null,this);
        }else if(optEnum == DbOptEnum.UPDATE){
            this.zslKeyValuePanel = new ZslKeyValuePanel(this.keyEntity, this);
        }

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(this.zslKeyValuePanel, BorderLayout.CENTER);
        panel.add(this.initBtnPanel(), BorderLayout.SOUTH);

//        Box verticalBox = Box.createVerticalBox();
//        verticalBox.add(this.zslKeyValuePanel);
//        verticalBox.add(this.initBtnPanel());

        this.setContentPane(panel);

//        JPanel panel = new JPanel(new BorderLayout());
//        panel.add(this.zslKeyValuePanel, BorderLayout.CENTER);
//        panel.add(this.initBtnPanel(), BorderLayout.SOUTH);

//        this.setContentPane(panel);

        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.setVisible(true);
    }

    public static void showDialog(DbOptEnum optEnum, NodeEntity dbEntity, KeyEntity key){
        new ZslKeyChangeDialog(optEnum,dbEntity,key);
    }

    private JPanel initBtnPanel(){
        ActionListener actionListener = event -> {
            String actionCommand = event.getActionCommand();
            if(BtnOptEnum.CANCEL.getText().equals(actionCommand)){
                this.dispose();
            }else if(BtnOptEnum.CONFIRM.getText().equals(actionCommand)){
                String key = this.zslKeyValuePanel.getKey();
                String type = this.zslKeyValuePanel.getType();
                String value = this.zslKeyValuePanel.getValue();

                if(StringUtils.hasEmpty(key, value)){
                    DialogUtils.errorDialog(ZslRedisDesktopMainWindow.getMainWindow(),"key&value 不能为空！");
                    return;
                }

                if(DbOptEnum.ADD == this.optEnum){
                    this.doAddAction(key, value, type);
                }else if(DbOptEnum.UPDATE == this.optEnum){
                    boolean flag = DialogUtils.confirmDialog(ZslRedisDesktopMainWindow.getMainWindow(), "确定要执行" + this.optEnum.getText() + "操作么？");
                    if(flag){
                        this.doUpdateAction(key, value, type);
                    }
                }
            }
        };

        return ConfirmCancelBtnPanelBuilder.getInstance(actionListener);
    }

    private void doUpdateAction(String key, String value, String type) {
        RedisUtils.del(this.dbEntity.getUniqueId(),this.dbEntity.getDbIndex(),key);
        this.doAddAction(key,value,type);
    }

    private void doAddAction(String key, String value, String type) {
        try{
            boolean result = false;
            if(RedisTypeEnum.STRING.getType().equals(type)){
                result = RedisUtils.setString(this.dbEntity.getUniqueId(), this.dbEntity.getDbIndex(), key, value, null);
            }else if(RedisTypeEnum.HASH.getType().equals(type)){
                JSONObject jsonObject = JSON.parseObject(value);

                Map<String,String> params = new HashMap<>();
                for(String k: jsonObject.keySet()){
                    params.put(k, jsonObject.getString(k));
                }
                result = RedisUtils.setHash(this.dbEntity.getUniqueId(),this.dbEntity.getDbIndex(),key,params);
            }else if(RedisTypeEnum.LIST.getType().equals(type)){
                String[] params = JSON.parseArray(value, String.class).toArray(new String[0]);
                result = RedisUtils.setList(this.dbEntity.getUniqueId(),this.dbEntity.getDbIndex(),key, params);
            }else if(RedisTypeEnum.SET.getType().equals(type)){
                String[] params = JSON.parseArray(value, String.class).toArray(new String[0]);
                result = RedisUtils.setSet(this.dbEntity.getUniqueId(),this.dbEntity.getDbIndex(),key, params);
            }else if(RedisTypeEnum.ZSET.getType().equals(type)){
                JSONObject jsonObject = JSON.parseObject(value);
                Map<String,Double> params = new HashMap<>();
                for(String k: jsonObject.keySet()){
                    params.put(k, jsonObject.getDouble(k));
                }

                result = RedisUtils.setZSet(this.dbEntity.getUniqueId(),this.dbEntity.getDbIndex(),key,params);
            }

            if(result){
                DialogUtils.msgDialog(ZslRedisDesktopMainWindow.getMainWindow(),this.optEnum.getText() +"操作成功！");
                this.dispose();
            }else{
                DialogUtils.errorDialog(ZslRedisDesktopMainWindow.getMainWindow(),this.optEnum.getText() +"操作失败！");
            }
        }catch (Exception e){
            ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
        }

    }


}
